﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using Willson.JsbManager.Bll;
using Willson.JsbManager.Comm;

namespace Willson.JsbManager.UI
{
    public partial class LoginForm : Form
    {
        private Boolean isLogin = false;
        private MainForm mainForm = null;
        
        public LoginForm(MainForm mainForm)
        {
            this.mainForm = mainForm;
            InitializeComponent();
        }

        private void LoginForm_Load(object sender, EventArgs e)
        {
            List<string> list = null;

            list = BLLFactory<BLLLogin>.Instance.GetUserList();

            try
            {
                ArgumentValidation.CheckForNullReference(list, "对象为空");
            }
            catch (ArgumentException ex)
            {
                MessageUtil.ShowError(ex.Message);
                return;
            }

            IEnumerator<string> ator = list.GetEnumerator();

            while (ator.MoveNext())
            {
                this.cbx_username.Items.Add(ator.Current.ToString());
            }

            this.cbx_username.SelectedIndex = 0;

         }

        private void bt_cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void LoginForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!isLogin) Application.Exit();
        }

        private void bt_login_Click(object sender, EventArgs e)
        {
            if (textBox_pwd.Text.Length == 0) return;

            if (!BLLFactory<BLLLogin>.Instance.Authentication(cbx_username.Text, textBox_pwd.Text))
            {
                MessageUtil.ShowWarning("用户验证失败!");
                textBox_pwd.Focus();
            }
            else
            {
                isLogin = true;

                int user_id = BLLFactory<BLLLogin>.Instance.GetUserID(cbx_username.Text);

                mainForm.Login(user_id, cbx_username.Text);
                this.Close();
            }
        }

        private void textBox_pwd_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) bt_login_Click(sender, e);
        }
    }
}
